import React, { useState, useEffect } from 'react';
import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input, message, Tabs } from 'antd';
import { useNavigate } from 'react-router-dom';
import { authService } from '../../services/auth';
import SliderCaptcha from '../../components/SliderCaptcha';
import './login.css'
import FaceLoginModal from './FaceLoginModal'

// 图片预加载函数
const preloadCaptchaImages = () => {
    // 预加载一些验证码图片
    const imageIds = [1, 2, 3, 4, 5, 10, 15, 20, 25, 30];
    imageIds.forEach(id => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.src = `https://picsum.photos/id/${id}/300/170`;
    });
};

type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
};

const App: React.FC = () => {
    const navigate = useNavigate();
    const [captchaOpen, setCaptchaOpen] = useState(false);
    const [loginFormData, setLoginFormData] = useState<FieldType | null>(null);
    const [faceOpen, setFaceOpen] = useState(false);
    const [activeTab, setActiveTab] = useState('password');

    // 页面加载时预加载验证码图片
    useEffect(() => {
        preloadCaptchaImages();
    }, []);

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        // 保存表单数据，准备进行拼图验证
        setLoginFormData(values);
        setCaptchaOpen(true);
    };

    const handleCaptchaSuccess = async () => {
        if (!loginFormData) return;

        try {
            await authService.login(loginFormData.username as string, loginFormData.password as string);
            message.success('登录成功');
            navigate('/mySelf', { replace: true });
        } catch {
            message.error('用户名或密码错误');
        } finally {
            setCaptchaOpen(false);
            setLoginFormData(null);
        }
    };

    const handleCaptchaClose = () => {
        setCaptchaOpen(false);
        setLoginFormData(null);
    };

    // Gitee第三方登录处理函数
    const handleGiteeLogin = () => {
        const clientId = '503f5bb7174ff4b93b1e69b1301a00065196a08533cc20b341d890620cbbe08a'; // 您的Gitee Client ID
        const redirectUri = encodeURIComponent('http://localhost:5173/auth/gitee/callback');
        const scope = 'user_info';

        const authUrl = `https://gitee.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}`;

        // 跳转到Gitee授权页面
        window.location.href = authUrl;
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = () => { };

    // 账号密码登录组件
    const PasswordLoginForm = () => (
        <div className="login-tab-content">
            <div className="login-title">
                <h1>账号密码登录</h1>
                <p>请输入您的登录信息</p>
            </div>

            <Form
                name="basic"
                className="login-form"
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Form.Item<FieldType>
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名!' }]}
                >
                    <Input placeholder="请输入用户名" />
                </Form.Item>

                <Form.Item<FieldType>
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: '请输入密码!' }]}
                >
                    <Input.Password placeholder="请输入密码" />
                </Form.Item>

                <Form.Item<FieldType> name="remember" valuePropName="checked" className="remember-me">
                    <Checkbox>记住我</Checkbox>
                </Form.Item>

                <Form.Item>
                    <Button className="login-btn" htmlType="submit">
                        登录
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );

    // 第三方登录组件
    const ThirdPartyLogin = () => (
        <div className="login-tab-content">
            <div className="login-title">
                <h1>第三方登录</h1>
                <p>选择您喜欢的登录方式</p>
            </div>

            <div className="third-party-login">
                <div className="third-party-buttons">
                    <Button
                        type="default"
                        className="third-party-btn gitee-login-btn"
                        onClick={handleGiteeLogin}
                    >
                        <img src="/gitee-icon.png" alt="Gitee图标" />
                        <span>Gitee登录</span>
                    </Button>
                    <Button
                        type="default"
                        className="third-party-btn face-login-btn"
                        onClick={() => setFaceOpen(true)}
                    >
                        <img src="/camera-icon.png" alt="人脸识别" />
                        <span>人脸识别登录</span>
                    </Button>
                </div>
            </div>
        </div>
    );

    // 标签页配置
    const tabItems = [
        {
            key: 'password',
            label: '账号密码',
            children: <PasswordLoginForm />
        },
        {
            key: 'thirdparty',
            label: '第三方登录',
            children: <ThirdPartyLogin />
        }
    ];

    return (
        <div className="login-container">
            <div className="login-card">
                <Tabs
                    activeKey={activeTab}
                    onChange={setActiveTab}
                    items={tabItems}
                    className="login-tabs"
                    centered
                />

                <SliderCaptcha
                    open={captchaOpen}
                    onClose={handleCaptchaClose}
                    onPassed={handleCaptchaSuccess}
                />
                <FaceLoginModal
                    open={faceOpen}
                    onClose={() => setFaceOpen(false)}
                    onSuccess={() => {
                        // 识别通过后，直接模拟登录并跳转
                        authService.login('user', '123456')
                            .then(() => {
                                message.success('人脸识别登录成功')
                                setFaceOpen(false)
                                navigate('/mySelf', { replace: true })
                            })
                            .catch(() => message.error('登录失败'))
                    }}
                />
            </div>
        </div>
    );
}

export default App;